<template>
  <view class="container">
    <!-- 头部统计 -->
    <view class="stats-container">
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-number">{{ taskStats.total }}</text>
          <text class="stat-label">总任务数</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ taskStats.inProgress }}</text>
          <text class="stat-label">进行中</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ taskStats.todo }}</text>
          <text class="stat-label">待办</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ taskStats.completed }}</text>
          <text class="stat-label">已完成</text>
        </view>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view class="filter-group">
        <text class="filter-label">按负责人</text>
        <picker mode="selector" :range="assignees" range-key="name" @change="onAssigneeChange">
          <view class="filter-select">{{ selectedAssignee?.name || '选择负责人' }}</view>
        </picker>
      </view>
      <view class="filter-group">
        <text class="filter-label">按优先级</text>
        <picker mode="selector" :range="priorities" range-key="name" @change="onPriorityChange">
          <view class="filter-select">{{ selectedPriority?.name || '选择优先级' }}</view>
        </picker>
      </view>
      <view class="filter-group">
        <text class="filter-label">按状态</text>
        <picker mode="selector" :range="statuses" range-key="name" @change="onStatusChange">
          <view class="filter-select">{{ selectedStatus?.name || '选择状态' }}</view>
        </picker>
      </view>
    </view>

    <!-- 任务列表 -->
    <scroll-view class="task-groups" scroll-y="true">
      <view v-for="group in taskGroups" :key="group.title" class="task-group">
        <view class="group-header">
          <text class="group-title">{{ group.title }}</text>
          <view class="group-stats">
            <view class="group-stat">
              <text class="group-stat-label">总计</text>
              <text class="group-stat-number">{{ group.tasks.length }}</text>
            </view>
            <view class="group-stat priority-stat" :class="getHighestPriority(group.tasks)">
              <text class="group-stat-label">{{ getPriorityText(getHighestPriority(group.tasks)) }}</text>
              <text class="group-stat-number">{{ countTasksByPriority(group.tasks, getHighestPriority(group.tasks)) }}</text>
            </view>
            <view class="group-stat status-stat" :class="getMostStatus(group.tasks)">
              <text class="group-stat-label">{{ getStatusText(getMostStatus(group.tasks)) }}</text>
              <text class="group-stat-number">{{ countTasksByStatus(group.tasks, getMostStatus(group.tasks)) }}</text>
            </view>
          </view>
        </view>
        <scroll-view class="task-cards" scroll-x="true">
          <TaskCard 
            v-for="task in group.tasks" 
            :key="task.id" 
            :task="task"
            @click="onTaskClick(task)"
          />
        </scroll-view>
      </view>
    </scroll-view>

    <!-- 添加任务按钮 -->
    <view class="add-task-btn" @click="onAddTask">
      <uni-icons type="plus" size="24" color="#fff"></uni-icons>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import TaskCard from '../../components/TaskCard.vue'
import type { Task, TaskStatistics, Assignee, Priority, Status } from '../../types/task'
import { taskApi } from '../../services/task'

// 数据状态
const tasks = ref<Task[]>([])
const assignees = ref<Assignee[]>([])
const priorities = ref<Priority[]>([])
const statuses = ref<Status[]>([])
const loading = ref(false)
const error = ref('')

// 选中的筛选条件
const selectedAssignee = ref<Assignee>({
  id: 'all',
  name: '全部',
  avatar: ''
})
const selectedPriority = ref<Priority>({
  id: 'all',
  name: '全部',
  color: ''
})
const selectedStatus = ref<Status>({
  id: 'all',
  name: '全部',
  color: ''
})

// 获取任务列表
const fetchTasks = async () => {
  try {
    loading.value = true
    const response = await taskApi.getTasks()
    tasks.value = response.tasks
  } catch (err) {
    error.value = err instanceof Error ? err.message : '获取任务列表失败'
    uni.showToast({
      title: error.value,
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

// 获取选项数据
const fetchOptions = async () => {
  try {
    const options = await taskApi.getOptions()
    assignees.value = [
      { id: 'all', name: '全部', avatar: '' },
      ...options.assignees
    ]
    priorities.value = [
      { id: 'all', name: '全部', color: '' },
      ...options.priorities
    ]
    statuses.value = [
      { id: 'all', name: '全部', color: '' },
      ...options.statuses
    ]
  } catch (err) {
    error.value = err instanceof Error ? err.message : '获取选项数据失败'
    uni.showToast({
      title: error.value,
      icon: 'error'
    })
  }
}

// 任务统计
const taskStats = computed(() => {
  return {
    total: tasks.value.length,
    inProgress: tasks.value.filter(t => t.status.name === '进行中').length,
    todo: tasks.value.filter(t => t.status.name === '待处理').length,
    completed: tasks.value.filter(t => t.status.name === '已完成').length
  }
})

// 任务分组
const taskGroups = computed(() => {
  const filtered = tasks.value.filter(task => {
    const matchAssignee = selectedAssignee.value.id === 'all' || task.assignee === selectedAssignee.value.id
    const matchPriority = selectedPriority.value.id === 'all' || task.priority.id === selectedPriority.value.id
    const matchStatus = selectedStatus.value.id === 'all' || task.status.id === selectedStatus.value.id
    return matchAssignee && matchPriority && matchStatus
  })

  const groups: Record<string, Task[]> = {}
  filtered.forEach(task => {
    const assignee = assignees.value.find(a => a.id === task.assignee)?.name || task.assignee
    if (!groups[assignee]) {
      groups[assignee] = []
    }
    groups[assignee].push(task)
  })

  return Object.entries(groups).map(([assignee, tasks]) => ({
    title: `${assignee}的任务`,
    tasks
  }))
})

// 事件处理
const onAssigneeChange = (e: any) => {
  selectedAssignee.value = assignees.value[e.detail.value]
}

const onPriorityChange = (e: any) => {
  selectedPriority.value = priorities.value[e.detail.value]
}

const onStatusChange = (e: any) => {
  selectedStatus.value = statuses.value[e.detail.value]
}

const onTaskClick = (task: Task) => {
  navigateToDetail(task.id)
}

const onAddTask = () => {
  navigateToCreate()
}

// 页面加载时获取数据
onMounted(async () => {
  await Promise.all([fetchTasks(), fetchOptions()])
})

// 下拉刷新
const onPullDownRefresh = async () => {
  await fetchTasks()
  uni.stopPullDownRefresh()
}

// 导航方法
const navigateToDetail = (taskId: string) => {
  uni.navigateTo({
    url: `/pages/task/detail?id=${taskId}`
  })
}

const navigateToCreate = () => {
  uni.navigateTo({
    url: '/pages/task/create'
  })
}

// 辅助方法
const getHighestPriority = (tasks: Task[]): Priority => {
  if (!tasks.length || !priorities.value.length) return priorities.value[1] // 跳过"全部"选项

  const priorityOrder = ['high', 'medium', 'low']
  const highestPriorityTask = tasks.reduce((highest, task) => {
    if (!highest || !task.priority) return highest
    const currentPriorityIndex = priorityOrder.indexOf(task.priority.id)
    const highestPriorityIndex = priorityOrder.indexOf(highest.priority?.id || 'low')
    return currentPriorityIndex < highestPriorityIndex ? task : highest
  }, tasks[0])

  return highestPriorityTask?.priority || priorities.value[1]
}

const getMostStatus = (tasks: Task[]): Status => {
  if (!tasks.length || !statuses.value.length) return statuses.value[1] // 跳过"全部"选项

  const statusCounts = tasks.reduce((acc, task) => {
    if (!task.status) return acc
    const statusId = task.status.id
    acc[statusId] = (acc[statusId] || 0) + 1
    return acc
  }, {} as Record<string, number>)

  const [mostCommonStatusId] = Object.entries(statusCounts)
    .sort(([, a], [, b]) => b - a)[0] || ['todo', 0]

  return statuses.value.find(s => s.id === mostCommonStatusId) || statuses.value[1]
}

const countTasksByPriority = (tasks: Task[], priority: Priority): number => {
  if (!tasks.length || !priority) return 0
  return tasks.filter(t => t.priority?.id === priority.id).length
}

const countTasksByStatus = (tasks: Task[], status: Status): number => {
  if (!tasks.length || !status) return 0
  return tasks.filter(t => t.status?.id === status.id).length
}

const getPriorityText = (priority: Priority): string => {
  if (!priority) return '未知'
  return priority.name
}

const getStatusText = (status: Status): string => {
  if (!status) return '未知'
  return status.name
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.stats-container {
  padding: 32rpx;
  background: #fff;
  margin-bottom: 24rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24rpx;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        font-size: 48rpx;
        font-weight: 600;
        color: #3b82f6;
        margin-bottom: 8rpx;
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #64748b;
      }
    }
  }
}

.filter-bar {
  padding: 24rpx 32rpx;
  background: #fff;
  margin-bottom: 24rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  gap: 24rpx;
  
  .filter-group {
    flex: 1;
    
    .filter-label {
      font-size: 24rpx;
      color: #64748b;
      margin-bottom: 8rpx;
      display: block;
    }
    
    .filter-select {
      padding: 16rpx;
      background: #f8fafc;
      border-radius: 8rpx;
      font-size: 28rpx;
      color: #475569;
    }
  }
}

.task-groups {
  flex: 1;
  height: 0;
  padding: 0 32rpx;
  
  // 垂直滚动条样式
  &::-webkit-scrollbar {
    width: 8rpx;
  }
  
  &::-webkit-scrollbar-track {
    background-color: #fff;
  }
  
  &::-webkit-scrollbar-thumb {
    background-color: #fff;
    border-radius: 4rpx;
    transition: background-color 0.3s;
  }
  
  &:hover {
    &::-webkit-scrollbar-thumb {
      background-color: rgba(144, 147, 153, 0.3);
      
      &:hover {
        background-color: rgba(144, 147, 153, 0.5);
      }
    }
  }
  
  .task-group {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 24rpx;
    
    .group-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16rpx;
      
      .group-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #2c3e50;
      }
      
      .group-stats {
        display: flex;
        gap: 16rpx;
        
        .group-stat {
          display: flex;
          align-items: center;
          padding: 4rpx 16rpx;
          border-radius: 32rpx;
          background: #f1f5f9;
          
          .group-stat-label {
            font-size: 24rpx;
            color: #64748b;
            margin-right: 8rpx;
          }
          
          .group-stat-number {
            font-size: 24rpx;
            font-weight: 600;
            color: #3b82f6;
          }
          
          &.priority-stat {
            &.high {
              background: rgba(#f56c6c, 0.1);
              .group-stat-label, .group-stat-number {
                color: #f56c6c;
              }
            }
            
            &.medium {
              background: rgba(#e6a23c, 0.1);
              .group-stat-label, .group-stat-number {
                color: #e6a23c;
              }
            }
            
            &.low {
              background: rgba(#409eff, 0.1);
              .group-stat-label, .group-stat-number {
                color: #409eff;
              }
            }
          }
          
          &.status-stat {
            &.todo {
              background: rgba(#909399, 0.1);
              .group-stat-label, .group-stat-number {
                color: #909399;
              }
            }
            
            &.inProgress {
              background: rgba(#409eff, 0.1);
              .group-stat-label, .group-stat-number {
                color: #409eff;
              }
            }
            
            &.completed {
              background: rgba(#67c23a, 0.1);
              .group-stat-label, .group-stat-number {
                color: #67c23a;
              }
            }
          }
        }
      }
    }
    
    .task-cards {
      white-space: nowrap;
      padding: 8rpx 0;
      
      // 水平滚动条样式
      &::-webkit-scrollbar {
        height: 8rpx;
      }
      
      &::-webkit-scrollbar-track {
        background-color: #fff;
      }
      
      &::-webkit-scrollbar-thumb {
        background-color: #fff;
        border-radius: 4rpx;
        transition: background-color 0.3s;
      }
      
      &:hover {
        &::-webkit-scrollbar-thumb {
          background-color: rgba(144, 147, 153, 0.3);
          
          &:hover {
            background-color: rgba(144, 147, 153, 0.5);
          }
        }
      }
    }
  }
}

.add-task-btn {
  position: fixed;
  right: 48rpx;
  bottom: 48rpx;
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #4b6cb7, #182848);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.15);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 100;
  
  &:active {
    transform: scale(0.95);
  }
}
</style>
